﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SqlCon;

namespace yfxt
{
    public partial class gl_dbsq : Form
    {
        public gl_dbsq()
        {
            InitializeComponent();
        }

        public string mbyf;
        string comStr;
        int tijiao_var = 0;               // 变量，控制“提交”按钮是否执行代码
        int queren_var = 0;               // 变量，控制“确认”按钮是否执行代码
        int delete_var = 0;               // 变量，控制“删除”按钮是否执行代码
        public string shenqingdanhao;       //传值比 增加按钮 窗体

        #region 增加按钮，
        private void button2_Click(object sender, EventArgs e)
        {
            gl_dbsqd dbsqd = new gl_dbsqd();
            dbsqd.Owner = this;
            mbyf = comboBox1.Text.ToString();
            dbsqd.ShowDialog();
        }
        #endregion

        #region 退出按钮，
        private void button6_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion

        /// <summary>
        /// 刷新函数              ---显示左和右DatagridView
        /// </summary>
        private void xianshi_DatagridView()
        {
            //左边DataGridView
            DataTable dt1 = new DataTable();
            comStr = "select sqdh,sqrq,CASE tjbz WHEN 0 THEN '未提交' when 1 then '已提交' when 2 then '已退回' END,CASE ckbz WHEN 0 THEN '未确认' when 1 then '已确认' END,bzxx " +
                "from YF_DB01 where rkbz=0 and sqyf='" + mainform.yfsb + "' and mbyf=(select yfsb from yf_yflb where yfmc='" + comboBox1.Text + "') " +
                "order by tjbz desc,ckbz desc,sqdh";
            dt1.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
            dataGridView1.Rows.Clear();
            if (dt1.Rows.Count > 0)
            {
                dataGridView1.Rows.Add(dt1.Rows.Count);
                for (int i = 0; i < dt1.Rows.Count; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        if (j!=1)
                        {
                            dataGridView1.Rows[i].Cells[j].Value = dt1.Rows[i][j].ToString();
                        }
                        else
                        {
                            dataGridView1.Rows[i].Cells[j].Value = Convert.ToDateTime(dt1.Rows[i][j]).ToString("yyyy-MM-dd").Replace('-', '.');
                        }
                    }
                }
            }

            //右边DataGridView
            DataTable dt2 = new DataTable();
            comStr = "select sqdh,rkrq,bzxx from YF_DB01 where rkbz=1 and sqyf='" + mainform.yfsb + "' and "+
                "mbyf=(select yfsb from yf_yflb where yfmc='" + comboBox1.Text + "')";
            dt2.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
            dataGridView2.Rows.Clear();
            if (dt2.Rows.Count > 0)
            {
                dataGridView2.Rows.Add(dt2.Rows.Count);
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    dataGridView2.Rows[i].Cells[0].Value = dt2.Rows[i][0].ToString();
                    dataGridView2.Rows[i].Cells[1].Value = Convert.ToDateTime(dt2.Rows[i][1]).ToString("yyyy-MM-dd").Replace('-', '.');
                    dataGridView2.Rows[i].Cells[2].Value = dt2.Rows[i][2].ToString();
                }
            }

            #region datagridView默认不选中单元格，使之成蓝色
            if (dataGridView1.Rows.Count > 0)
            {
                dataGridView1.Rows[0].Selected = false;
            }
            if (dataGridView2.Rows.Count > 0)
            {
                dataGridView2.Rows[0].Selected = false;
            }
            #endregion
        }

        private void gl_dbsq_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToResizeRows = false;                     //禁止用鼠标调整datagridView单元格的大小。
            dataGridView1.AllowUserToResizeColumns = false;
            dataGridView2.AllowUserToResizeRows = false;                     //禁止用鼠标调整datagridView单元格的大小。
            dataGridView2.AllowUserToResizeColumns = false;
            foreach (DataGridViewColumn c in dataGridView1.Columns)        //禁止对datagridView列进行排序
            {
                c.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            foreach (DataGridViewColumn c in dataGridView2.Columns)        //禁止对datagridView列进行排序
            {
                c.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            //目标药房
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            DataTable dt = new DataTable();
            comStr = "select yfmc from yf_yflb where yfsb!=" + mainform.yfsb + " and yfsb!=2";
            dt.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                comboBox1.Items.Add(dt.Rows[i][0]);
            }
            comboBox1.Text = dt.Rows[0][0].ToString();

            xianshi_DatagridView();
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (delete_var == 1)
            {
                if (dataGridView1.Rows.Count > 0)
                {
                    if (dataGridView1.CurrentRow.Cells[2].Value.ToString() != "已提交")
                    {
                        if (MessageBox.Show("是否删除调拨申请单" + "" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "" + "？",
                            "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {
                            string Delete_sqdh = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                            try
                            {
                                //删除两张表 ---调拨表和调拨明细表
                                string comStr = "delete from YF_DB01 where sqdh='" + Delete_sqdh + "';" +
                                    "delete from YF_DB02 where sqdh='" + Delete_sqdh + "'";
                                SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                                xianshi_DatagridView();
                                MessageBox.Show("删除调拨申请单" + "" + Delete_sqdh + "" + "成功！");
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message.ToString());
                            }
                        }
                        else
                        {
                            delete_var = 0;
                            for (int i = 0; i < dataGridView1.Rows.Count; i++)
                            {

                                dataGridView1.Rows[i].Selected = false;
                            }
                        }
                    }
                }
            }           
        }

        /// <summary>
        /// 提交按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (tijiao_var == 1)
            {
                if (dataGridView1.Rows.Count > 0)
	            {
        		     if (dataGridView1.CurrentRow.Cells[2].Value.ToString() != "已提交")
	                {
                        if (MessageBox.Show("是否提交调拨申请单" + "" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "" + "？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {
                            try
                            {
                                comStr = "update YF_DB01 set tjbz='1',czgh='" + Program.ygbh + "',sqrq='" + DateTime.Now.ToString() + "' where sqdh='" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'";
                                SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                                xianshi_DatagridView();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message.ToString());
                            }
                        }
                        else
                        {
                            tijiao_var = 0;
                            for (int i = 0; i < dataGridView1.Rows.Count; i++)
                            {

                                dataGridView1.Rows[i].Selected = false;
                            }
                        }
	                }
	            }  
            }
        }

        /// <summary>
        /// 刷新按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region 刷新按钮
        private void button1_Click(object sender, EventArgs e)
        {
            xianshi_DatagridView();
        }
        #endregion

        /// <summary>
        /// 确认按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (queren_var == 1)
            {
                if (dataGridView1.Rows.Count > 0)
                {
                    if (dataGridView1.CurrentRow.Cells[2].Value.ToString() == "已提交" && dataGridView1.CurrentRow.Cells[3].Value.ToString() == "已确认")
                    {
                        if (MessageBox.Show("是否确认调拨申请单" + "" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "" + "？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                        {
                            try
                            {
                                comStr = "update YF_DB01 set rkbz='1',rkgh='" + Program.ygbh + "',rkrq='" + DateTime.Now.ToString() + "' where sqdh='" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'";
                                SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);

                                ////药房库存表 增加库存   
                                DataTable dt2 = new DataTable();                             
                                comStr = "select qrsl,sqyf,ypxh,ypcd,lsjg,lsje,qrsl from YF_DB02 " +
                                    "where sqdh='" + dataGridView1.CurrentRow.Cells[0].Value.ToString() + "'";
                                dt2.Load(SqlHelper.ExecuteReader(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null));
                                for (int i = 0; i < dt2.Rows.Count; i++)
                                {
                                    decimal qrsl = Convert.ToDecimal(dt2.Rows[i][0]);
                                    string sqyf = dt2.Rows[i][1].ToString();
                                    string ypxh = dt2.Rows[i][2].ToString();
                                    string ypcd = dt2.Rows[i][3].ToString();
                                    string lsjg = dt2.Rows[i][4].ToString();
                                    string lsje = dt2.Rows[i][5].ToString();
                                    //update，yf_kcmx的库存
                                    //comStr = "update t1 set t1.ypsl=t1.ypsl+'" + qrsl + "' from yf_kcmx t1 where " +
                                    //"t1.ypxh='" + ypxh + "' and t1.yfsb='" + sqyf + "' and t1.ypph='" + ypph + "'";
                                //    int res = SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                                    //如果update不到，insert， yf_kcmx的库存
                                    //if (res < 1)
                                    //{
                                        comStr = "select max(ypph)+1 from yf_kcmx";   //不使用自增的sbxh作为主键了，用（ypph+ypxh+yfsb）
                                        string ypph = (SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null)).ToString();

                                        comStr = "insert into yf_kcmx(ypph,ypsl,yfsb,ypxh,ypcd,lsjg,lsje,ypsl) values('" + ypph + "','" + qrsl + "'," +
                                            "'" + sqyf + "','" + ypxh + "','" + ypcd + "','" + lsjg + "','" + lsje + "','" + qrsl + "')";
                                        SqlHelper.ExecuteNonQuery(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, comStr, null);
                                    //}
                                }
                                xianshi_DatagridView();
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message.ToString());
                            }
                        }
                        else
                        {
                            queren_var = 0;
                            for (int i = 0; i < dataGridView1.Rows.Count; i++)
                            {

                                dataGridView1.Rows[i].Selected = false;
                            }
                        }
                    }
                }
            }            
        }

        #region 显示调拨申请单
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            shenqingdanhao = dataGridView1.CurrentRow.Cells[0].Value.ToString();
            if (dataGridView1.CurrentRow.Cells[2].Value.ToString()=="未提交")
            {
                gl_dbsqd_zuo ypckd_zuo = new gl_dbsqd_zuo();
                ypckd_zuo.Owner = this;
                ypckd_zuo.ShowDialog();
            }
            else
            {
                gl_dbsqd_zuo1 dbsqd_zuo1 = new gl_dbsqd_zuo1();
                dbsqd_zuo1.Owner = this;
                dbsqd_zuo1.ShowDialog();
            }
        }

        private void dataGridView2_KeyDown(object sender, KeyEventArgs e)
        {
            shenqingdanhao = dataGridView2.CurrentRow.Cells[0].Value.ToString();
            gl_dbsqd_you dbsqd_you = new gl_dbsqd_you();
            dbsqd_you.Owner = this;
            dbsqd_you.ShowDialog();
        }
        #endregion

        //变量，控制“提交”按钮是否执行代码
        private void dataGridView1_Enter(object sender, EventArgs e)
        {
            tijiao_var = 1;
            queren_var = 1;
            delete_var = 1;
        }

        #region datagridView失去焦点，单元格不显示蓝色
        private void dataGridView1_Leave(object sender, EventArgs e)
        {
            if (!button5.Focused)
            {
                queren_var = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    dataGridView1.Rows[i].Selected = false;
                }
            }

            if (!button4.Focused)
            {
                tijiao_var = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    dataGridView1.Rows[i].Selected = false;
                }
            }

            if (!button3.Focused)
            {
                delete_var = 0;
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    dataGridView1.Rows[i].Selected = false;
                }
            }

            //方法2：
            //this.dataGridView1.ClearSelection();
            //this.dataGridView1.TabStop = false;

            //方法3：this.dataGridView1.CurrentCell = null;
        }

        private void dataGridView2_Leave(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {

                dataGridView2.Rows[i].Selected = false;
            }
        }
        #endregion

        //窗体重新获取焦点，发生的刷新事件
        private void gl_dbsq_Paint(object sender, PaintEventArgs e)
        {
            xianshi_DatagridView();
        }

        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            xianshi_DatagridView();
        }
        
    }
}
